import os
import re  # 添加正则表达式模块

def filter_log_file(file_path):
    """
    过滤指定日志文件中状态码不为 200 的行，并覆盖原文件。
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()

        original_count = len(lines)  # 记录原始行数
        
        # 使用正则表达式匹配状态码为 200 的行
        # 日志格式：IP - - [时间] "请求" 状态码 大小 "..." "..."
        status_pattern = r'"[^"]*"\s+200\s+'  # 匹配引号结束后跟状态码200的模式
        filtered_lines = [line for line in lines if re.search(status_pattern, line)]

        deleted_count = original_count - len(filtered_lines)  # 计算删除的行数

        with open(file_path, 'w', encoding='utf-8') as file:
            file.writelines(filtered_lines)

        print(f"已处理并覆盖文件: {file_path}，原始 {original_count} 行，保留 {len(filtered_lines)} 行，删除 {deleted_count} 行。")

    except Exception as e:
        print(f"处理文件 {file_path} 时出错: {e}")

def main():
    current_dir = os.getcwd()  # 获取当前工作目录
    log_files = [f for f in os.listdir(current_dir) if f.endswith('.log')]

    if not log_files:
        print("当前目录没有找到 .log 文件。")
        return

    for log_file in log_files:
        file_path = os.path.join(current_dir, log_file)
        filter_log_file(file_path)

if __name__ == "__main__":
    main()
